package com.lnj.community.interceptor;


import com.lnj.community.config.JwtConfig;
import com.lnj.community.dao.entity.User;
import com.lnj.community.service.RedisTokenService;
import com.lnj.community.service.UserService;
import com.lnj.community.utiles.CommunityConstant;
import com.lnj.community.utiles.HostHolder;
import com.lnj.community.utiles.JwtUtil;
import com.lnj.community.utiles.RedisKeyUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Collection;

/**
 * jwt令牌校验的拦截器
 */
@Component
public class JwtTokenUserInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtConfig jwtProperties;
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final Logger log= LoggerFactory.getLogger(JwtTokenUserInterceptor.class);

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行

            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());
        if (token == null) {
            token = getTokenFromCookie(request);
        }

        //先去redis中查询token是否存在
        String redisKey = RedisKeyUtil.getTokenKey(token);
        if (redisTemplate.hasKey(redisKey)) {
            User user =(User) redisTemplate.opsForValue().get(redisKey);
            //ThreadLocal 用于保存当前登录用户id，以用于后续的业务操作
            HostHolder.setUser(user);
            //构建用户认证结果 并且存入到SecurityContextHolder中 以便于security进行权限认证
            Authentication authentication = new UsernamePasswordAuthenticationToken(
                    user, user.getPassword(), userService.getAuthorities(user.getId()));
            SecurityContextHolder.setContext(new SecurityContextImpl(authentication));
            // 直接使用 authentication 参数，无需调用 get() 方法
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            //3、通过，放行
            return true;
        }


        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            int userId = Integer.valueOf(claims.get(CommunityConstant.USER_ID).toString());
            log.info("当前员工id：{}", userId);
            //由id获取用户信息，存入ThreadLocal

            User user = userService.findUserById(userId);
            if (user == null) {
                log.error("当前访问用户不存在: {}", userId);
                throw new RuntimeException("当前访问用户不存在");
            }

            //ThreadLocal 用于保存当前登录用户id，以用于后续的业务操作
            HostHolder.setUser(user);
            //构建用户认证结果 并且存入到SecurityContextHolder中 以便于security进行权限认证
            Authentication authentication = new UsernamePasswordAuthenticationToken(
                    user, user.getPassword(), userService.getAuthorities(user.getId()));
            SecurityContextHolder.setContext(new SecurityContextImpl(authentication));

            // 直接使用 authentication 参数，无需调用 get() 方法
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //3、通过，放行
            return true;
        }
    }
    // 在模板引擎之前执行，将用户信息封装到model中
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = HostHolder.getUser();
        if (user != null && modelAndView != null) {
            modelAndView.addObject("loginUser", user);
        }
    }

    // 在模板引擎之后执行，清理ThreadLocal中的用户信息
    @Override
    public void afterCompletion(jakarta.servlet.http.HttpServletRequest request, jakarta.servlet.http.HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HostHolder.clear();
        //SecurityContextHolder.clearContext();
    }

    private String getTokenFromCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("lnj_token".equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
